/*
 * @Author: HX
 * @Date: 2024-12-05 13:30:58
 * @LastEditors: HX
 * @LastEditTime: 2024-12-12 15:33:41
 */
import uuid from './uuid.js';
import { log2ssmapObj } from './common.js';
let Store = function Store() {
	this._state = Object.create(null);
	this.entityId = null;
};

Store.prototype.add = function (data, key) {
	let uid = uuid();
	key || (this.entityId = uid);
	key = key ? key : uid;
	this._state[key] = data;
	return key;
};

Store.prototype.set = function (data, key) {
	key = key ? key : this.entityId;
	this._state[key] = data;
};

Store.prototype.get = function (key) {
	return this._state[key];
};

Store.prototype.getEntity = function () {
	return this._state[this.entityId];
};

Store.prototype.has = function (key) {
	return key in this._state;
};

Store.prototype.remove = function (keys, parent) {
	keys = Array.isArray(keys) ? keys : [keys];
	keys.forEach((key) => {
		let state = this._state;
		let instance = state[key];
		if (instance && instance.delete) {
			if (parent) {
				instance.entity.delete ? instance.entity.delete() : instance.delete();
			} else {
				instance.delete();
			}
		}
		delete state[key];
	});
};

Store.prototype.removeAll = function (parent) {
	let state = this._state;
	for (const key in state) {
		let instance = state[key];
		if (instance && instance.delete) {
			parent ? instance.entity.delete() : instance.delete();
		}
		delete state[key];
	}
	this._state = Object.create(null);
};

Store.prototype.getAll = function () {
	return this._state;
};

Store.prototype.getAllKey = function () {
	let keyList = [];
	for (const key in this._state) {
		keyList.push(key);
	}
	return keyList;
};

export default Store;
